<script lang='ts'  setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import api from '@/api';
import { ElMessage, ElMessageBox, FormRules } from 'element-plus'

// 查询条件
const query = ref<{ roleName: string }>({ roleName: '' })
// 查询表单的 ref
const queryFormRef = ref()
const roles = ref<{
    _id?: string
    createTime: string
    permissionList: {
        checkedKeys: string[]
        halfCheckedKeys: string[]
    }
    remark: string
    roleName: string
}[]>()
const handleQuery = async () => {
    const { data: res } = await api.roleApi(query.value, 'get')
    roles.value = res.list
}
// 表格列
const columns = reactive<{ prop: string, label: string, formatter?: Function }[]>([
    { prop: 'roleName', label: '角色名称' },
    { prop: 'remark', label: '备注' },
    { prop: 'createTime', label: '创建时间' },
])


// dialog
const editMode = ref(false)
const dialogVisible = ref(false)
const roleFormRef = ref()
const roleFormRules = ref<FormRules>({
    roleName: [
        { required: true, message: '角色名称必须填写', trigger: 'blur' }
    ]
})
const createRole = ref<{
    roleName?: string
    remark?: string
    id?: string
    permissionList?: {
        checkedKeys: string[]
        halfCheckedKeys: string[]
    }
}>({})
// 菜单树ref
const menusTreeRef = ref()
// TODO 默认所有菜单展开
const extendKeys = ref()

const handleClose = () => {
    ElMessageBox.confirm(
        `确定退出${editMode ? '编辑' : '创建'}角色吗？`,
        `${editMode ? '编辑' : '创建'}角色`,
        {
            showClose: false,
            cancelButtonText: '取消',
            confirmButtonText: '确定',
        }
    )
        .then(() => {
            // done()
            dialogVisible.value = false
            roleFormRef.value.resetFields()
            delete createRole.value.id
            delete createRole.value.permissionList
            // 取消roleTree的选中状态
            menusTreeRef.value.setCheckedKeys([])
        })
        .catch(() => { })
}

const handleSave = () => {
    roleFormRef.value.validate(async (isValid: boolean) => {
        if (isValid) {
            const nodes: any[] = menusTreeRef.value.getCheckedNodes()
            const halfKeys = menusTreeRef.value.getCheckedKeys()
            const checkedKeys: string[] = []
            const parentKeys: string[] = []
            nodes.forEach(node => {
                if (node.children) {
                    parentKeys.push(node._id)
                } else {
                    checkedKeys.push(node._id)
                }
            })
            createRole.value.permissionList = {
                checkedKeys,
                halfCheckedKeys: [...parentKeys, ...halfKeys]
            }
            try {
                await api.roleApi(createRole.value, editMode.value ? 'put' : 'post')
            } catch (error) {
                ElMessage.error(`操作失败：${error}`)
            }

            ElMessage.success(`成功${editMode.value ? '修改' : '创建'}角色`)
            roleFormRef.value.resetFields()
            menusTreeRef.value.setCheckedKeys([])
            handleQuery()
            dialogVisible.value = false
            delete createRole.value.id
            delete createRole.value.permissionList
        }
    })


}

const handleEdit = (row: any) => {
    createRole.value.id = row._id
    dialogVisible.value = editMode.value = true
    nextTick(() => {
        createRole.value.roleName = row.roleName
        createRole.value.remark = row.remark
        // 使用微任务 否则在创建完毕之前就执行了
        nextTick(() => {
            menusTreeRef.value.setCheckedKeys(row.permissionList.checkedKeys)
        })
    })
}


const handleDel = (row: any) => {
    ElMessageBox.confirm(
        `确认删除角色[${row.roleName}]吗？`, '提示',
        { cancelButtonText: '取消', confirmButtonText: '确定' })
        .then(async () => {
            await api.roleApi({ _id: row._id }, 'delete')
            ElMessage.success('成功删除角色')
            handleQuery()
        }).catch(() => { })
}


// 所有菜单
const menus = ref()

onMounted(async () => {
    menus.value = await (await api.getMenuListApi({ menuState: 1 })).data
    handleQuery()
})
</script>

<template>
    <div id='RoleManage'>
        <div class=" p-[20px] pb-0   card overflow-hidden ">
            <!-- 条件查询表单区域 -->
            <el-form inline :model="query" ref="queryFormRef">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input placeholder="请输入角色名称" v-model.trim="query.roleName" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleQuery">查询</el-button>
                    <el-button type="danger" @click="queryFormRef.resetFields()">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class=" h-[20px] bg-slate-50" />

        <div class=" card ">
            <!-- 操作区域 -->
            <div class=" p-[20px]">
                <el-button type="primary" @click="editMode = false; dialogVisible = true">创建</el-button>
            </div>
            <!-- 表格正文 -->
            <el-table :data="roles" max-height="500px" row-key="_id" size="default">
                <!-- 循环渲染表格列 -->
                <el-table-column v-for="column in columns" :key="column.prop" :prop="column.prop" :label="column.label"
                    :formatter="column.formatter" />
                <el-table-column label="操作" width="150px" fixed="right">
                    <template #default="scope">
                        <el-button type="primary" @click="handleEdit(scope.row)">编辑</el-button>
                        <el-button type="danger" @click="handleDel(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>


        <el-dialog v-model="dialogVisible" :title="`${editMode ? '编辑' : '创建'}角色`" width="30%"
            :before-close="handleClose" :show-close="false">

            <el-form :model="createRole" label-width="auto" ref="roleFormRef" :rules="roleFormRules">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="createRole.roleName" placeholder="请输入角色名称" />
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input type="textarea" v-model="createRole.remark" placeholder="请输入备注" />
                </el-form-item>
                <el-form-item label="选择权限">
                    <el-tree-v2 node-key="_id" :data="menus" :default-expanded-keys="extendKeys" show-checkbox
                        ref="menusTreeRef" :props="{ value: '_id', label: 'menuName' }" class="w-full" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="handleClose" size="default">取消</el-button>
                    <el-button type="primary" @click="handleSave" size="default">{{ editMode ? '保存' : '创建' }}
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>
